var baseConfig = require("../../baseConfig");
Page({
  data: {
    top_banner: [{
        image: "http://fcdn.qiushilaile.com/game/default-99211634010791227.jpg",
        url: "/pages/activity/activity",
        id: 3
      }, {
        image: "http://fcdn.qiushilaile.com/game/default-74411624950296990.jpg",
        url: "/pages/videoTutorial/videoTutorial",
        id: 2
      },
      // {
      //   image: "/static/banner_example.png",
      //   url: "/pages/problem/problem",
      //   id: 1
      // },
    ],
    layer1Popup: false,
    ic: 'rgba(255, 255, 255, .3)',
    iac: '#fff',
    popupList: [],
  },
  onLoad: function (options) {
    this.getPopupData();
    // this.getDate();
    this.getData();
    // console.log("home=options==",JSON.stringify(options))
    var userId = options.id
    if (options.scene) {
      const scene = decodeURIComponent(options.scene)
      console.log("home=scene==", scene)
      if (scene) {
        userId = scene.split("=")[1]
      }
      console.log("userId===", userId)
    }
    if (userId) {
      wx.setStorageSync('inviteCode', userId)
    }
  },
  onShow() {
    this.setData({
      collectmini: false,
    })
    this.getData();
    // console.log('vip身份', wx.getStorageSync('tuserInfo').role);
  },
  onReady() {
    this.setData({
      collectmini: true,
    })
  },
  getPopupData() {
    wx.request({
      url: baseConfig.baseUrl + 'get_system_notice_window',
      success: res => {
        console.log(res.data.data);
        if (res.data.data == '') {
          this.setData({
            layerPopup: false
          })
        } else {
          // console.log(this.data.layerPopup);
          if (wx.getStorageSync('date')) {
            var today = new Date();
            var yesterday_milliseconds = today.getTime();
            var yesterday = new Date();
            yesterday.setTime(yesterday_milliseconds);
            var strDay = yesterday.getDate();
            var strMonth = yesterday.getMonth() + 1;
            var Year = yesterday.getFullYear();
            var Month = strMonth < 10 ? "0" + strMonth : strMonth;
            var Day = strDay < 10 ? "0" + strDay : strDay;
            const daily = Year + "-" + Month + "-" + Day;
            console.log('当天时间', daily);
            let localDate = wx.getStorageSync('date')
            console.log('本地缓存时间', localDate);
            if (localDate == daily) {
              console.log('同一天 不展示弹窗');
              this.setData({
                layerPopup: false,
              })
            } else {
              console.log('第二天 展示弹窗 设置日期到localstorage');
              wx.setStorageSync('date', daily);
              this.setData({
                layerPopup: true,
                noticeTitle: res.data.data[0].title,
                noticeContent: res.data.data[0].content,
              })
            }
          } else {
            this.setData({
              layerPopup: true,
              noticeTitle: res.data.data[0].title,
              noticeContent: res.data.data[0].content,
            })
            console.log(this.data.layerPopup);
            this.getDate();
          }
        }
      }
    })
  },
  toSystemBulletin() {
    console.log('前往系统公告');
    wx.navigateTo({
      url: '/pages/systemBulletin/systemBulletin',
    })
  },
  getDate() { // 获取当天日年月日并判断是否同一天
    var today = new Date();
    var yesterday_milliseconds = today.getTime();
    var yesterday = new Date();
    yesterday.setTime(yesterday_milliseconds);
    var strDay = yesterday.getDate();
    var strMonth = yesterday.getMonth() + 1;
    var Year = yesterday.getFullYear();
    var Month = strMonth < 10 ? "0" + strMonth : strMonth;
    var Day = strDay < 10 ? "0" + strDay : strDay;
    const daily = Year + "-" + Month + "-" + Day;
    console.log('当天时间', daily);
    // this.setData({
    //   yearMonthDay: daily
    // });
    let localDate = wx.getStorageSync('date')
    console.log('本地缓存时间', localDate);
    if (localDate == daily) {
      console.log('同一天 不展示弹窗');
    } else {
      console.log('第二天 展示弹窗 设置日期到localstorage');
      wx.setStorageSync('date', daily);
      // this.getPopupData();
    }
  },
  testImg(e) {
    console.log(wx.getStorageSync('tuserInfo').role);
    let {
      appid,
      goodsid,
      name,
      test_icon,
      test_name,
      logo
    } = e.currentTarget.dataset;
    if (wx.getStorageSync('userInfo') == "") {
      wx.showToast({
        icon: "loading",
        title: "请先登录",
        duration: 1000
      })
      setTimeout(() => {
        wx.switchTab({
          url: "/pages/me/me"
        })
      }, 1000)
      return
    } else if (wx.getStorageSync('tuserInfo').role != "USER") {
      wx.showModal({
        title: '提示',
        content: '请先激活会员',
        success(res) {
          if (res.confirm) {
            wx.switchTab({
              url: "../me/me"
            });
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return
    } else {
      console.log(e.currentTarget.dataset);
      wx.navigateTo({
        url: '/pages/testImg/testImg?appid=' + appid +
          '&logo=' + logo +
          '&goodsId=' + goodsid +
          '&name=' + name +
          '&test_icon=' + test_icon +
          '&test_name=' + test_name,
      })
    }

  },
  clickSearch() {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
  toClose() { // 点击关闭提示收藏消息
    this.setData({
      collectmini: false,
    })
  },
  topBannerTap(e) { // 前往新手教程
    console.log(e.currentTarget.dataset);
    if (e.currentTarget.dataset.id == '1') {
      wx.navigateTo({
        url: "../problem/problem"
      })
    } else if (e.currentTarget.dataset.id == '2') {
      wx.navigateTo({
        url: "../videoTutorial/videoTutorial"
      })
    } else if (e.currentTarget.dataset.id == '3') {
      wx.navigateTo({
        url: "../activity/activity?userId=" + wx.getStorageSync('userid')
      })
    }
  },
  getData() {
    wx.request({
      url: baseConfig.baseUrl + 'goods/appgoodsmode/page?p=0&f=5&is_weixin=0',
      success: res => {
        wx.setStorageSync('productList', res.data.data.content)
        this.setData({
          productList: res.data.data.content,
          // totalCount: res.data.data.total
        });
      }
    })
  },
  getKuaishouNum() {
    wx.request({
      url: baseConfig.url + `baseSelect/kuaishou_id_select`,
      method: 'POST',
      data: {
        is_weixin: 2
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
        "UID": wx.getStorageSync("userid")
      },
      success: res => {
        var newArr = []
        res.data.data.forEach((item, index) => {
          newArr.push(item.name)
        })
        console.log(newArr);
        this.setData({
          array1: newArr
        })
        if (res.data.data == '') {
          console.log('newArr为空，白名单未配置');
        } else {
          this.setData({
            whiteList: true
          })
          console.log('whiteList值为：', this.data.whiteList);
        }
      }
    })
  },
  lookDetailClick(e) {
    console.log(wx.getStorageSync('tuserInfo').role);
    if (wx.getStorageSync('userInfo') == "") {
      wx.showToast({
        icon: "loading",
        title: "请先登录",
        duration: 1000
      })
      setTimeout(() => {
        wx.switchTab({
          url: "/pages/me/me"
        })
      }, 1000)
      return
    } else if (wx.getStorageSync('tuserInfo').role != "USER") {
      wx.showModal({
        title: '提示',
        content: '请先激活会员',
        success(res) {
          if (res.confirm) {
            return wx.switchTab({
              url: "../me/me"
            });
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return
    } else {
      let t = wx.getStorageSync('productList');
      let {
        appId,
        desc,
        icon,
        name
      } = t[e.currentTarget.dataset.index]
      var appGoodsSimpleInfos = JSON.stringify(t[e.currentTarget.dataset.index].appGoodsSimpleInfos);
      wx.navigateTo({
        url: `/pages/productDetail/productDetail?appId=${appId}&desc=${desc}&icon=${icon}&total=${this.data.total}&name=${name}&is_weixin=0&appGoodsSimpleInfos=${encodeURIComponent(appGoodsSimpleInfos)}`,
      });
    }
  },
  pushDouYinByMyself(e) {
    console.log(wx.getStorageSync('tuserInfo').role);
    if (wx.getStorageSync('userInfo') == "") {
      wx.showToast({
        icon: "loading",
        title: "请先登录",
        duration: 1000
      })
      setTimeout(() => {
        wx.switchTab({
          url: "/pages/me/me"
        })
      }, 1000)
      return
    } else if (wx.getStorageSync('tuserInfo').role != "USER") {
      wx.showModal({
        title: '提示',
        content: '请先激活会员',
        success(res) {
          if (res.confirm) {
            wx.switchTab({
              url: "../me/me"
            });
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return
    } else {
      this.douyinDownClick(e);
    }
  },
  tuiGuang(e) {
    console.log(wx.getStorageSync('tuserInfo').role);
    if (wx.getStorageSync('userInfo') == "") {
      wx.showToast({
        icon: "loading",
        title: "请先登录",
        duration: 1000
      })
      setTimeout(() => {
        wx.switchTab({
          url: "/pages/me/me"
        })
      }, 1000)
      return
    } else if (wx.getStorageSync('tuserInfo').role != "USER") {
      wx.showModal({
        title: '提示',
        content: '请先激活会员',
        success(res) {
          if (res.confirm) {
            wx.switchTab({
              url: "../me/me"
            });
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return
    } else {
      console.log('111', e.currentTarget.dataset);
      let goodsId = e.currentTarget.dataset.goodsid;
      let appid = e.currentTarget.dataset.appid;
      wx.request({
        url: baseConfig.baseUrl + `qrcode/tt/${appid}`,
        method: "GET",
        data: {
          is_weixin: 0,
          goodsId: goodsId
        },
        header: {
          "Authorization": wx.getStorageSync('token'),
          "UID": wx.getStorageSync('userid'),
          'Content-Type': 'application/json'
        },
        success: res => {
          this.setData({
            layer1Popup: true,
            imgUrl: res.data.data
          })
        }
      })
    }

  },
  tuiGuangGame1(e) {
    console.log('111', e.currentTarget.dataset);
    let goodsId = e.currentTarget.dataset.goodsid;
    console.log(goodsId);
    let appid = e.currentTarget.dataset.appid;
    console.log(appid);
    this.setData({
      dialog: true,
      tg_goodsId: goodsId,
      tg_appid: appid,
    });
  },
  tuiGuangGame2(e) {
    let appid = this.data.tg_appid
    let goodsId = this.data.tg_goodsId
    this.setData({
      dialog: false
    });
    wx.request({
      url: baseConfig.baseUrl + `qrcode/tt/${appid}`,
      method: "GET",
      data: {
        is_weixin: 0,
        goodsId: goodsId
      },
      header: {
        "Authorization": wx.getStorageSync('token'),
        "UID": wx.getStorageSync('userid'),
        'Content-Type': 'application/json'
      },
      success: res => {
        this.setData({
          layer1Popup: true,
          imgUrl: res.data.data
        })
      }
    })
  },
  douyinDownClick(e) {
    console.log(e.currentTarget.dataset);
    let t = wx.getStorageSync('productList');
    let appid = t[e.currentTarget.dataset.index].appId;
    wx.request({
      url: baseConfig.baseUrl + `qrcode/tt/${appid}`,
      method: "GET",
      data: {
        is_weixin: 0,
        goodsId: 0
      },
      header: {
        "Authorization": wx.getStorageSync('token'),
        "UID": wx.getStorageSync('userid'),
        'Content-Type': 'application/json'
      },
      success: res => {
        this.setData({
          layer1Popup: true,
          imgUrl: res.data.data
        })
      }
    })
  },
  douYinCloseClick() {
    this.setData({
      layerPopup: false,
      layer1Popup: false,
      dialog: false
    })
  },
  closeClick() {
    this.setData({
      layer1Popup: false,
    })
  },
  jiaochengClick() {
    wx.navigateTo({
      url: "../problem/problem"
    })
  },
  saveImage(filePath) {
    var aa = wx.getFileSystemManager();
    aa.writeFile({
      filePath: wx.env.USER_DATA_PATH + '/test.png',
      data: this.data.imgUrl,
      encoding: 'base64',
      success: res => {
        wx.saveImageToPhotosAlbum({
          filePath: wx.env.USER_DATA_PATH + '/test.png',
          success: function (res) {
            wx.showToast({
              title: '保存成功',
            })
          },
          fail: function (err) {
            console.log(err)
          }
        })
        console.log(res)
      },
      fail: err => {
        console.log(err)
      }
    })
  },
  saveImageToPhotos(filePath) {
    let self = this
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              self.saveImage(filePath)
              self.isGetSet = true
            },
            fail() {
              self.isGetSet = false
            }
          })
        } else {
          self.isGetSet = true
          self.saveImage(filePath)
        }
      },
      fail(res) {
        console.log(res);
      }
    })
  },
  onReachBottom: function () { // 页面上拉触底事件的处理函数
    wx.showToast({
      title: '没有更多了~',
      icon: "none"
    })
  },
  onShareTimeline: function (res) {
    return {
      title: '欢迎来到推蛙,赚取短视频收益',
      path: '/pages/home/home',
    }
  },
  onShareAppMessage: function (res) {
    return {
      title: '欢迎来到推蛙,赚取短视频收益',
      path: '/pages/home/home',
    }
  }
})